package com.mingqijia.gassafety.job.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mingqijia.gassafety.db.entity.WorkOrderHistory;
import com.mingqijia.gassafety.db.mapper.WorkOrderHistoryMapper;
import com.mingqijia.gassafety.job.response.AsstOrderListResponse;
import com.mingqijia.gassafety.job.service.WorkOrderHistoryService;
import com.mingqijia.gassafety.shared.constant.AsstConstants;
import com.mingqijia.gassafety.shared.utils.HttpUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 工单记录表 服务实现类
 * </p>
 *
 * @author guoliang.lao
 * @since 2022-09-15
 */
@Service
@Slf4j
public class WorkOrderHistoryServiceImpl extends ServiceImpl<WorkOrderHistoryMapper, WorkOrderHistory> implements WorkOrderHistoryService {

    @Value(value = "${asst.workOrder.doamin.url}")
    String workOrderUrl;
    @Autowired
    HttpUtil httpUtil;

    @Override
    public void updateHandleStatusByOrderNo() {
        log.info("updateHandleStatusByOrderNo start");
        LambdaQueryWrapper<WorkOrderHistory> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WorkOrderHistory::getIsDeleted,0)
                .eq(WorkOrderHistory::getHandleStatus,0)
                .orderByDesc(WorkOrderHistory::getCreatedAt);
        List<WorkOrderHistory> list = this.list(queryWrapper);

        List<String> orderNos = list.stream().map(WorkOrderHistory::getOrderNo).collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(orderNos)) {
            List<AsstOrderListResponse> orderList = getOrderList(orderNos,null);
            for (WorkOrderHistory history : list) {
                for (AsstOrderListResponse asstOrderListResponse : orderList) {
                    if (history.getOrderNo().equals(asstOrderListResponse.getOrderNo()) && (asstOrderListResponse.getOrderStatus().equals(60) ||
                            asstOrderListResponse.getOrderStatus().equals(70))) {
                        WorkOrderHistory newHis = new WorkOrderHistory();
                        newHis.setId(history.getId());
                        newHis.setHandleStatus(1);
                        this.updateById(newHis);
                        log.info("更新工单处理状态："+newHis.toString());
                    }
                }
            }
        }
        log.info("updateHandleStatusByOrderNo end");
    }

    /**
     * 根据工单号和工单状态查询工单列表
     * @param orderNos
     * @param orderStatuses
     */
    private List<AsstOrderListResponse> getOrderList(List<String> orderNos, List<Integer> orderStatuses) {
        log.info("getOrderList start");
        try {
            Map map = new HashMap();
            map.put("orderNos",orderNos);
            if (!CollectionUtils.isEmpty(orderStatuses)) {
                map.put("orderStatuses",orderStatuses);
            }
            map.put("page",1);
            map.put("pageSize",10000);
            String url = workOrderUrl + AsstConstants.ORDER_LIST_URL;
            String body = httpUtil.getBody(JSONObject.toJSONString(map), url,null);
            log.info("根据工单号和工单状态查询工单列表:"+body);
            JSONObject jsonObject = JSONObject.parseObject(body);
            if (jsonObject.get("code").equals(0)) {
                List<AsstOrderListResponse> res = JSON.parseArray(jsonObject.getString("data"), AsstOrderListResponse.class);
                return res;
            } else {
                log.error(jsonObject.get("msg").toString());
            }
        } catch (Exception e) {
            log.error("根据工单号和工单状态查询工单列表查询失败",e);
        }
        return new ArrayList<>();
    }
}
